﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MusicAcademy
{
    public partial class frmTerm : Form
    {
        private int recordID = -1;
        public  int TeacherID = -1;
        private int ToolID = -1;
        private int ClassID = -1;

        public frmTerm()
        {
            InitializeComponent();
        }

        private void RefreshGrid()
        {
            if (chkContainsSearch.Checked)
                this.fullTermTableAdapter.Fill(this.musicAcademyDataSet2.FullTerm, txtLastNameSearch.Text, txtToolSearch.Text, -1, Program.academyID);
            else
                this.fullTermTableAdapter.FillByStarting(this.musicAcademyDataSet2.FullTerm, txtLastNameSearch.Text, txtToolSearch.Text, -1, Program.academyID);
        }


        private void frmTerm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'musicAcademyDataSet.WeekDays' table. You can move, or remove it, as needed.
            this.weekDaysTableAdapter.Fill(this.musicAcademyDataSet.WeekDays);

            if (UserManager.HasAccess("frmTerm", "View") == false)
            {
                MessageBox.Show("شما اجازه ی دیدن این فرم را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            RefreshGrid();
            cmbIsGroup.SelectedIndex = 0;
            cmbEnabled.SelectedIndex = 1;
        }

        private bool isSessionValid()
        {
            bool valid = true;
            if (ClassID == -1)
                valid = Globals.SetError(txtClass);
            else
                Globals.SetValid(txtClass);

            if (txtTime.Text.IndexOf("_") >= 0 || Globals.IsValidTime(txtTime.Text) == false)
                valid = Globals.SetError(txtTime);
            else
                Globals.SetValid(txtTime);

            return valid;
        }

        private bool isValid()
        {
            bool valid = true;
            if (TeacherID == -1)
                valid = Globals.SetError(txtTeacher);
            else
                Globals.SetValid(txtTeacher);

            if (ToolID == -1)
                valid = Globals.SetError(txtTool);
            else
                Globals.SetValid(txtTool);

            if (txtDate.IsValidDate() == false)
                valid = Globals.SetError(txtDate);
            else
                Globals.SetValid(txtDate);

            if (txtTeachTime.Text  == "")
                valid = Globals.SetError(txtTeachTime);
            else
                Globals.SetValid(txtTeachTime);

            if (txtCount.Text == "")
                valid = Globals.SetError(txtCount);
            else
                Globals.SetValid(txtCount);

            if (txtPercent.Text == "" || int.Parse(txtPercent.Text) < 1 || int.Parse(txtPercent.Text) > 100)
                valid = Globals.SetError(txtPercent);
            else
                Globals.SetValid(txtPercent);

            if (txtCost.Text == "")
                valid = Globals.SetError(txtCost);
            else
                Globals.SetValid(txtCost);

            return valid;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            int dayID;
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;

            com.Connection = con;
            if (isValid() == false)
                return;

            if (recordID == -1)
            {
                if (UserManager.HasAccess("frmTerm", "Insert") == false)
                {
                    MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }


                com.CommandType = System.Data.CommandType.Text;

                dayID = Convert.ToInt32(cmbDay.SelectedValue);

                com.CommandText = "insert into Term(academyID,cost,days,isGroup,startDate,teacherID,teacherPercent,teachingTime,toolID,enable,creator,createDate) values (@academyID,@cost,@days,@isGroup,@startDate,@teacherID,@teacherPercent,@teachingTime,@toolID,@enable,@creator,@createDate); SELECT TOP 1 ID FROM  Term ORDER BY ID DESC";
                com.Parameters.AddWithValue("@academyID", Program.academyID);
                com.Parameters.AddWithValue("@cost", txtCost.Text);
                com.Parameters.AddWithValue("@days", txtCount.Text);
                com.Parameters.AddWithValue("@isGroup", cmbIsGroup.SelectedIndex);
                com.Parameters.AddWithValue("@startDate", txtDate.Text);
                com.Parameters.AddWithValue("@teacherID", TeacherID);
                com.Parameters.AddWithValue("@teacherPercent", txtPercent.Text);
                com.Parameters.AddWithValue("@teachingTime", txtTeachTime.Text);
                com.Parameters.AddWithValue("@toolID", ToolID);
                com.Parameters.AddWithValue("@enable", cmbEnabled.SelectedIndex);
                com.Parameters.AddWithValue("@creator", Program.userID);
                com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());

                con.Open();
                dreader = com.ExecuteReader();
                dreader.Read();
                recordID = Convert.ToInt32(dreader["ID"]);
                pnlAddSession.Enabled = true;
                btnClass.Enabled = true;
                com.Parameters.Clear();
                dreader.Close();

                con.Close();

                RefreshGrid();
            }
            else
            {
                if (UserManager.HasAccess("frmTeachers", "Update") == false)
                {
                    MessageBox.Show("شما اجازه ی ویرایش کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                com.CommandType = System.Data.CommandType.Text;

                dayID = Convert.ToInt32(cmbDay.SelectedValue);

                com.CommandText = "update Term set cost=@cost, days=@days, isGroup=@isGroup, startDate=@startDate, teacherID=@teacherID, teacherPercent=@teacherPercent, teachingTime=@teachingTime, toolID=@toolID, enable=@enable, lastEditor=@lastEditor, editDate=@editDate where ID=@ID;";

                com.Parameters.AddWithValue("@ID", recordID);
                com.Parameters.AddWithValue("@cost", txtCost.Text);
                com.Parameters.AddWithValue("@days", txtCount.Text);
                com.Parameters.AddWithValue("@isGroup", cmbIsGroup.SelectedIndex);
                com.Parameters.AddWithValue("@startDate", txtDate.Text);
                com.Parameters.AddWithValue("@teacherID", TeacherID);
                com.Parameters.AddWithValue("@teacherPercent", txtPercent.Text);
                com.Parameters.AddWithValue("@teachingTime", txtTeachTime.Text);
                com.Parameters.AddWithValue("@toolID", ToolID);
                com.Parameters.AddWithValue("@enable", cmbEnabled.SelectedIndex);
                com.Parameters.AddWithValue("@lastEditor", Program.userID);
                com.Parameters.AddWithValue("@editDate", Globals.Get10CharDate());
                com.Parameters.AddWithValue("@DOW", dayID);
                com.Parameters.AddWithValue("@time", txtTime.Text);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();

                RefreshGrid();
            }
            MessageBox.Show("ذخیره شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            btnDelete.Enabled = true;
        }

        private void grdTerm_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            Globals.SetValid(txtTeacher);
            Globals.SetValid(txtTool);
            Globals.SetValid(txtDate);
            Globals.SetValid(txtTeachTime);
            Globals.SetValid(txtCount);
            Globals.SetValid(txtPercent);
            Globals.SetValid(txtCost);
            Globals.SetValid(txtTime);
            Globals.SetValid(txtClass);

            recordID = Convert.ToInt32(grdTerm.Rows[e.RowIndex].Cells["ID"].Value);
            TeacherID = Convert.ToInt32(grdTerm.Rows[e.RowIndex].Cells["_teacherID"].Value);
            ToolID = Convert.ToInt32(grdTerm.Rows[e.RowIndex].Cells["_toolID"].Value);

            txtTeacher.Text = grdTerm.Rows[e.RowIndex].Cells["FullName"].FormattedValue.ToString();
            txtTool.Text = grdTerm.Rows[e.RowIndex].Cells["toolName"].Value.ToString();
            txtDate.Text = grdTerm.Rows[e.RowIndex].Cells["startDate"].Value.ToString();
            txtTeachTime.Text = grdTerm.Rows[e.RowIndex].Cells["teachingTime"].Value.ToString();
            txtPercent.Text = grdTerm.Rows[e.RowIndex].Cells["teacherPercent"].Value.ToString();
            txtCost.Text = grdTerm.Rows[e.RowIndex].Cells["cost"].Value.ToString();
            txtCount.Text = grdTerm.Rows[e.RowIndex].Cells["days"].Value.ToString();
            cmbIsGroup.SelectedIndex = Convert.ToInt32(grdTerm.Rows[e.RowIndex].Cells["isGroup"].Value);
            cmbEnabled.SelectedIndex = Convert.ToInt32(grdTerm.Rows[e.RowIndex].Cells["_enable"].Value);
            btnDelete.Enabled = true;

            fullTermProgramTableAdapter.Fill(musicAcademyDataSet.FullTermProgram, recordID);
            pnlAddSession.Enabled = true;
            btnClass.Enabled = true;
        }



        private void ClearForm()
        {
            recordID = -1;
            txtClass.Text = "";
            txtCost.Text = "";
            txtCount.Text = "12";
            txtDate.Text = "";
            txtPercent.Text = "";
            txtTeacher.Text = "";
            txtTeachTime.Text = "";
            txtTime.Text = "";
            txtTool.Text = "";
            cmbDay.SelectedIndex = 0;

            fullTermProgramTableAdapter.Fill(musicAcademyDataSet.FullTermProgram, recordID);

            btnDelete.Enabled = false;

            pnlAddSession.Enabled = false;
            btnClass.Enabled = false;

            Globals.SetValid(txtTeacher);
            Globals.SetValid(txtTool);
            Globals.SetValid(txtDate);
            Globals.SetValid(txtTeachTime);
            Globals.SetValid(txtCount);
            Globals.SetValid(txtPercent);
            Globals.SetValid(txtCost);
            Globals.SetValid(txtTime);
            Globals.SetValid(txtClass);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();

            if (UserManager.HasAccess("frmTerm", "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (MessageBox.Show("آیا از حذف این رکورد اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                com.Connection = con;
                com.CommandType = CommandType.Text;

                com.CommandText = "delete from TermProgram where termID=@ID; delete from Term where ID=@ID";
                com.Parameters.AddWithValue("@ID", recordID);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                ClearForm();
                RefreshGrid();

                MessageBox.Show("حذف شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnTeacher_Click(object sender, EventArgs e)
        {
            ListOfPersons p = new ListOfPersons();
            p.PersonType = 1;

            if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TeacherID = p.SelectedID;
                txtTeacher.Text = p.FirstName + " " + p.LastName;
                // RefreshGrid();
            }
        }

        private void btnTool_Click(object sender, EventArgs e)
        {
            ListOfTools t = new ListOfTools();
            if (t.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ToolID = t.SelectedID;
                txtTool.Text = t.ToolName;
            }
        }

        private void txtLastNameSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtToolSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtCost_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtCount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtTeachTime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtClassSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void grdTerm_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridViewRow row;
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            string s = "";

            if (grdTerm.Columns[e.ColumnIndex].Name == "TermProgram")
            {
                row = grdTerm.Rows[e.RowIndex];
                com.Connection = con;
                com.CommandType = CommandType.Text;
                com.CommandText = "SELECT TermProgram.time, WeekDays.dayName, classNumber FROM TermProgram INNER JOIN WeekDays ON TermProgram.DOW = WeekDays.ID INNER JOIN Class ON Class.ID=TermProgram.classID WHERE termID=@termID";
                com.Parameters.AddWithValue("@termID", row.Cells["ID"].Value);
                con.Open();
                dreader = com.ExecuteReader();
                while (dreader.Read())
                {
                    s += (s == "" ? "" : "  --  ") + dreader["dayName"].ToString() + " (" + dreader["time"].ToString() + ") ک:" + dreader["classNumber"].ToString();
                }
                e.Value = s;
                e.FormattingApplied = true;
                dreader.Close();
                con.Close();
            }
            else if (grdTerm.Columns[e.ColumnIndex].Name == "FullName")
            {
                row = grdTerm.Rows[e.RowIndex];
                e.Value = row.Cells["firstName"].Value + " " + row.Cells["lastName"].Value;
                e.FormattingApplied = true;
            }
        }

        private void btnClass_Click(object sender, EventArgs e)
        {
            ListOfClasses c = new ListOfClasses();
            if (c.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ClassID = c.SelectedID;
                txtClass.Text = c.ClassNumber;
            }
        }

        private void txtTime_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }

        private void cmbDay_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lblTime_Click(object sender, EventArgs e)
        {

        }

        private void lblDay_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnAddProgram_Click(object sender, EventArgs e)
        {
            if (UserManager.HasAccess("frmTerm", "Insert") == false)
            {
                MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (isSessionValid() == false)
                return;
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;

            com.CommandText = "INSERT INTO TermProgram(termID,DOW,time, classID, creator, createDate) values(@termID,@DOW,@time, @classID, @creator, @createDate)";
            com.Parameters.AddWithValue("@termID", recordID);
            com.Parameters.AddWithValue("@DOW", cmbDay.SelectedValue);
            com.Parameters.AddWithValue("@time", txtTime.Text);
            com.Parameters.AddWithValue("@classID", ClassID);
            com.Parameters.AddWithValue("@creator", Program.userID);
            com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());

            con.Open();
            com.ExecuteNonQuery();
            con.Close();

            fullTermProgramTableAdapter.Fill(musicAcademyDataSet.FullTermProgram, recordID);
            RefreshGrid();
        }

        private void btnDeleteProgram_Click(object sender, EventArgs e)
        {
            if (lstProgram.SelectedIndex == -1)
            {
                MessageBox.Show("لطفا یک رکورد از برنامه هفتگی را انتخاب کنید .", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (UserManager.HasAccess("frmTerm", "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (MessageBox.Show("آیا از حذف این رکورد از برنامه هفتگی اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandType = CommandType.Text;

                com.CommandText = "DELETE FROM TermProgram WHERE ID=@ID";
                com.Parameters.AddWithValue("@ID", lstProgram.SelectedValue);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();

                fullTermProgramTableAdapter.Fill(musicAcademyDataSet.FullTermProgram, recordID);
                RefreshGrid();

                Globals.SetValid(txtTime);
                Globals.SetValid(txtClass);
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            frmSessions s = new frmSessions();
            s.TermID = recordID;
            s.txtRegister.Text = "کلاس " + txtTool.Text + " - استاد " + txtTeacher.Text;
            s.ShowDialog();
        }

        private void grpTerm_Enter(object sender, EventArgs e)
        {

        }
    }
}
